import 'package:flutter/foundation.dart';
import 'package:get/get.dart';
import 'package:pornhub_app/components/diolog/dialog.dart';
import 'package:pornhub_app/components/diolog/loading/loading_view.dart';
import 'package:pornhub_app/http/http_service.dart';
import 'package:pornhub_app/utils/ad_jump.dart';
import 'package:pornhub_app/utils/logger.dart';

import 'enum_pay.dart';
import 'model/pay_link_model.dart';
import 'model/recharge_request_model.dart';
import 'model/recharge_type_model.dart';

import 'package:universal_html/html.dart' show window;
import 'package:universal_html/html.dart';

class PayUtils {
  /// 支付方式验证和发起支付
  static checkPay({
    required double amount,
    required int payNumber,
    required int purType,
    required int source,
    required int payId,
    required double balance,
    required RechargeTypeModel currentPayType,
    required Function()? onSuccess,
  }) async {
    if (currentPayType == RechargeTypeModel.empty()) {
      showToast("请选择支付方式");
      return;
    }

    PayType _payType;
    if (currentPayType.isAlipay) {
      _payType = PayTypeEnum.alipay;
    } else if (currentPayType.isWechat) {
      _payType = PayTypeEnum.wechat;
    } else if (currentPayType.isUnion) {
      _payType = PayTypeEnum.unionPay;
    } else {
      _payType = PayTypeEnum.balance;
    }

    RechargeRequestModel rechargeRequest = RechargeRequestModel(
      money: "$amount",
      nums: payNumber,
      purType: purType,
      rechType: _payType.toString(),
      source: source,
      targetId: payId,
    );

    if (_payType == PayTypeEnum.balance) {
      if (balance < amount) {
        showToast("余额不足");
        return;
      }
    }

    await startPay(rechargeRequest, onSuccess);
  }

  /// 发起支付
  static startPay(RechargeRequestModel request, Function()? onSuccess) async {
    await LoadingView.singleton.wrap(
      context: Get.context!,
      asyncFunction: () async {
        var newWindow;
        if (kIsWeb && request.rechType != '0') {
          newWindow = window.open('', '_blank');
        }

        try {
          final response = await httpInstance.post(
            url: 'rech/sumbit',
            body: request.toJson(),
            complete: PayLinkModel.fromJson,
          );

          if (request.rechType == "0") {
            onSuccess?.call();
          }

          if (response != null) {
            if (kIsWeb) {
              newWindow.location.href = response.url;
            } else {
              jumpExternalAddress(response.url, null);
            }
          }
        } catch (e) {
          logger.e(e);
        }
      },
    );
  }
}
